package com.example.heizhu.appfuncore.deeplinkdemo;

import android.content.Intent;
import android.net.ParseException;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.example.heizhu.appfuncore.R;

import core.android.deeplinks.deeplinking.AKDeeplink;
import core.android.deeplinks.deeplinking.annotations.DeeplinkQueryParameter;
import core.android.deeplinks.deeplinking.annotations.DeeplinkRoute;
import core.android.deeplinks.deeplinking.annotations.DeeplinkRouteParameter;


/**
 * 吊起方法：
 * adb shell am start -W -a "android.intent.action.VIEW" -d "http://www.http.com/products/45?referrer=b.com" com.example.heizhu.applinkdemo
 */
@DeeplinkRoute("products/:product_id")
public class ProductActivity extends AppCompatActivity {

    @DeeplinkRouteParameter("product_id")
    private int mProductId;

    @DeeplinkQueryParameter("referrer")
    public String mReferrer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product);
        AKDeeplink.INSTANCE.inject(this);

        Log.d(getLocalClassName(), "mProductId=" + mProductId + "  mReferrer=" + mReferrer);

        onNewIntent(getIntent());
    }

    /**
     * 检验该intent是否是deep link的intent。如果是则从intent数据从接触recipe的URI并调用
     * showRecipe()来展示菜谱。
     **/

    @Override
    protected void onNewIntent(Intent intent) {
        String action = intent.getAction();
        String data = intent.getDataString();

        Log.d(this.getLocalClassName(), "action=" + action);
        Log.d(this.getLocalClassName(), "data=" + data);


        if (Intent.ACTION_VIEW.equals(action) && data != null) {
            String recipeId = data.substring(data.lastIndexOf("/") + 1);
            Log.d(this.getLocalClassName(), "recipeId=" + recipeId);
        }

        Uri referrerUri = this.getReferrer();
        Log.d(this.getLocalClassName(), "referrerUri=" + referrerUri);
    }


    /**
     * 返回启动该Activity的引用者.
     */
    @Override
    public Uri getReferrer() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            return super.getReferrer();
        }
        return getReferrerCompatible();
    }

    /**
     * 在低于SDK 22版本时使用该方法获得引用者
     */
    private Uri getReferrerCompatible() {
        Intent intent = this.getIntent();
        Uri referrerUri = intent.getParcelableExtra(Intent.EXTRA_REFERRER);
        if (referrerUri != null) {
            return referrerUri;
        }
        String referrer = intent.getStringExtra("android.intent.extra.REFERRER_NAME");
        if (referrer != null) {
            // 尝试parse引用者URL
            try {
                return Uri.parse(referrer);
            } catch (ParseException e) {
                return null;
            }
        }
        return null;
    }

}


